<?php
/**
 * Crypter library
 *
 * Provides basic encryption/decryption for AD.
 * @package Packages
 */

/**
 *
 */
require_once(AD_SERVER_PATH . '/pkgs/init.php');

/**
 * Crypter library
 *
 * Provides basic encryption/decryption for AD.
 * @package Packages
 */
class CCrypter
{
	/**
	 * Initialize encrypter
	 *
	 * Opens and initializes encryption module.
	 * If you want this to be more secure key please see
	 * http://php.net/manual/en/function.mcrypt-create-iv.php
	 * @return string $mcm
	 */
	public static function init_crypter()
	{
		$mcm = mcrypt_module_open('rijndael-256', '', 'ofb', '');
		$iv = md5(AD_SECRET_KEY);

		$ks = mcrypt_enc_get_key_size($mcm);
		$key = substr($iv, 0, $ks);

		mcrypt_generic_init($mcm, $key, $iv);
		return $mcm;
	}

	/**
	 * Deinitialize encrypter
	 *
	 * Deinitializes and closes encryption module.
	 * @param address $mcm
	 */
	public static function deinit_crypter(& $mcm)
	{
		mcrypt_generic_deinit($mcm);
		mcrypt_module_close($mcm);
	}

	/**
	 * Encrypt
	 *
	 * Encrypts string passed as argument.
	 * @param string $clear_txt
	 * @return string $encoded_txt
	 */
	public static function encrypt($clear_txt)
	{
		if (TRUE == empty($clear_txt))
		{
			return $clear_txt;
		}
		$mcm = CCrypter::init_crypter();
		$encrypted = mcrypt_generic($mcm, $clear_txt);
		$encoded_txt = base64_encode($encrypted);
		CCrypter::deinit_crypter($mcm);

		return $encoded_txt;
	}

	/**
	 * Decrypt
	 *
	 * Decrypts string passed as argument.
	 * @param string $encoded_txt
	 * @return string $decrypted
	 */
	public static function decrypt($encoded_txt)
	{
		if (TRUE == empty($encoded_txt))
		{
			return $encoded_txt;
		}
		$mcm = CCrypter::init_crypter();
		$encrypted = base64_decode($encoded_txt);
		$decrypted = mdecrypt_generic($mcm, $encrypted);
		CCrypter::deinit_crypter($mcm);

		return $decrypted;
	}
}
